﻿using System;
using System.Data;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using System.Web.UI;
using System.Collections.Generic;
using System.Globalization;
using System.Collections;

public partial class CreditsPage : System.Web.UI.Page
{
    private readonly string mCurrentModule = Credits.Module.ID;
    private readonly string mPageName = "Administrarea Contragentilor";
    private string appPath = string.Empty;
    private const string EditCreditPanel = "EditCreditPanel";

    bool allowLoanView = false;
    bool allowLoanEdit = false;

    Credits.DataObjects.Client ClientObject
    {
        get { return Session["ClientObject"] != null ? (Credits.DataObjects.Client)Session["ClientObject"] : new Credits.DataObjects.Client(); }
        set { Session["ClientObject"] = value; }
    }

    private Credits.DataObjects.LoanObject CurrentCredit
    {
        get { return Session[this.ClientID + "CurrentCredit"] != null ? (Credits.DataObjects.LoanObject)Session[this.ClientID + "CurrentCredit"] : new Credits.DataObjects.LoanObject(); }
        set { Session[this.ClientID + "CurrentCredit"] = value; }
    }

    private List<Credits.DataObjects.Fidejusor> FidejusoriList
    {
        get { return Session[this.ClientID + "Fidejusori"] != null ? (List<Credits.DataObjects.Fidejusor>)Session[this.ClientID + "Fidejusori"] : new List<Credits.DataObjects.Fidejusor>(); }
        set
        {
            Session[this.ClientID + "Fidejusori"] = null;
            Session[this.ClientID + "Fidejusori"] = value; 
        }
    }

    private bool NewContract
    {
        get { return Session[this.ClientID + "currentCreditOperation"] != null ? (bool)Session[this.ClientID + "currentCreditOperation"] : false; }
        set { Session[this.ClientID + "currentCreditOperation"] = value; }
    }  

    protected void Page_Load(object sender, EventArgs e)
    {
        appPath = Utils.GetApplicationPath(Request);       
        Utils.GetMaster(this).PerformPreloadActions(mCurrentModule, mPageName);

        try
        {
            allowLoanView = Utils.PermissionAllowed(mCurrentModule, Credits.Domains.ManageLoans.Name, Constants.Constants.Classifiers.Permissions_View);
            allowLoanEdit = Utils.PermissionAllowed(mCurrentModule, Credits.Domains.ManageLoans.Name, Constants.Constants.Classifiers.Permissions_Edit);

            if (allowLoanView)
            {
                requestDateCalendarExtender.Format = Constants.Constants.ISODateBackwardDotsFormat;
                loanDataContractelorCalendarExtender.Format = Constants.Constants.ISODateBackwardDotsFormat;
                loandDataEliberariiCalendarExtender.Format = Constants.Constants.ISODateBackwardDotsFormat;
                dataScadenteiCalendarExtender.Format = Constants.Constants.ISODateBackwardDotsFormat;



                addNewloanButton.Visible = allowLoanEdit;
                saveLoanButton.Visible = allowLoanEdit;
                addGarantiiFidejusoriButton.Visible = allowLoanEdit;
                removeGarantiiFidejusoriButton.Visible = allowLoanEdit;
                comitetMemberFilter.Visible = allowLoanEdit;
                addGajIpotecaButton.Visible = allowLoanEdit;
                removeGajIpotecaButtonButton.Visible = allowLoanEdit;

                if (!IsPostBack)
                {
                    FillDLLOnAddEditForm();                    
                    gajControl.BindDataSource();

                    DataTable clientsDT = Utils.ModuleSecurity().UsersList();
                    comitetMemberFilter.DisplayValueField = "UserFullName";
                    comitetMemberFilter.DataValueFiled = "userid";
                    comitetMemberFilter.DataSource = clientsDT;
                    comitetMemberFilter.DataBind();

                    SetInitialRowForNewClientsTable(); //// for manuall edit grid view source table
                    CreateUpdateViewStateTables(); /////// viewstate for garantos, pledges, comitet aprob tables

                    contractPercentTextBox.Attributes.Add("onKeyUp", "CalculateAlernativePercent(this.value, '" + alternativePercentTextBox.ClientID + "');");
                    alternativePercentTextBox.Attributes.Add("onKeyUp", "CalculateAlernativePercent2(this.value, '" + contractPercentTextBox.ClientID + "');");


                    if (Request["cd"] != null && !Request["cd"].ToString().Equals(string.Empty))
                    {
                        int loanID = 0;
                        int.TryParse(Request["cd"].ToString(), out loanID);

                        Credits.DataObjects.LoanObject loanObject = Utils.ModuleCredits().GetLoanObjectByID(loanID);
                        Credits.DataObjects.Client clientObject = this.ClientObject;

                        if (clientObject == null || (loanObject != null && clientObject.ClientID != loanObject.ClientID))
                        {
                            clientObject = Utils.ModuleCredits().GetCleintObjectByID(loanObject.ClientID);
                            this.ClientObject = clientObject;
                        }

                        this.CurrentCredit = loanObject != null ? loanObject : new Credits.DataObjects.LoanObject();

                        if (Utils.GetMaster(this.Page).IsEmptyNavLinks)
                        {
                            Utils.GetMaster(this).AddNavlink("Clients", "../ModuleCredits/Clients.aspx", "ClientsPageID");
                            Utils.GetMaster(this).AddNavlink(clientObject.FirstName + " " + clientObject.LastName, "../ModuleCredits/Clients.aspx?clid=" + clientObject.ClientID, "clientID");
                        }

                        Utils.GetMaster(this).AddNavlink("Data:[" + this.CurrentCredit.LoanStartDate.ToString(Constants.Constants.ISODateBackwardDotsFormat) + " - " + this.CurrentCredit.LoanEndDate.ToString(Constants.Constants.ISODateBackwardDotsFormat) + "], Summa[" + this.CurrentCredit.ContractAmount + "], Procent:[" + this.CurrentCredit.ContrcatPercent + "]", "../ModuleCredits/Credits.aspx?cd=" + loanID, "creditID");
   
                        if (loanID > 0)
                        {
                            FillAddEditForm();
                            FillManualEditCreditGridView();
                            ShowPanel(EditCreditPanel);

                            this.NewContract = false;
                        }
                        else
                        {
                            ClearAddEditLoanForm();
                            ShowPanel(addEditCreditPanel.ID);
                        }                                        
                    }
                    else
                    {
                        loanSelectionDialog.BindDataSource();
                        ShowPanel(loanSelectionDialog.ID);
                    }
                }
                else
                {
                    string functionName = Request.Params.Get("__EVENTTARGET");

                    if (!functionName.Equals(string.Empty))
                    {
                        string inputParams = Request.Params.Get("__EVENTARGUMENT");
                        switch (functionName)
                        {
                            case "ShowMessages":
                                int loanID = 0;
                                int.TryParse(inputParams, out loanID);
                                SetLoanEditAviability();
                                loanComitetCommentControl.CurrentCredit = this.CurrentCredit;
                                loanComitetCommentControl.ComitetMembers = comitetMemberFilter.SelectedValuesAsInt;
                                loanComitetCommentControl.Show();
                                FillContractImprumutPrintForm();
                                break;

                            default:
                                break;
                        }
                    }
                }
            }
            else
            {
                Response.Redirect(Utils.GetApplicationPath(Request) + "/AccessDenied.aspx");
            }
        }
        catch (Exception ex)
        { Utils.InfoText(this, "Eroare in System!", ex.Message.ToString()); }         
    }
    
    protected void CreateUpdateViewStateTables()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("LoanID", typeof(int));
        dt.Columns.Add("pledgeID", typeof(int));
        dt.Columns.Add("denumirea", typeof(string));
        dt.Columns.Add("pledgeType", typeof(int));
        dt.Columns.Add("proprietar", typeof(int));
        dt.Columns.Add("address", typeof(string));
        dt.Columns.Add("description", typeof(string));
        dt.Columns.Add("pretpiata", typeof(int));
        dt.Columns.Add("sumagajata", typeof(int));
        dt.Columns.Add("ShortDescription", typeof(string));     
        ViewState["ipotGaj"] = dt;        
    }

    private void ShowPanel(string panelName)
    {
        #region Hide panels
        emptyPanel.Visible = false;
        creditAllDetailsPanel.Visible = false;
        loanSelectionDialog.Hide();

        addEditCreditPanel.Visible = false;
        #endregion Hide panels

        try
        {
            #region Get Panel Name

            switch (panelName)
            {
                case "loanSelectionDialog":
                    loanSelectionDialog.BindDataSource();
                    loanSelectionDialog.Show();
                    break;

                case "EditCreditPanel":
                    addEditCreditPanel.Visible = true;
                    creditAllDetailsPanel.Visible = true;
                    //usdChangeRatelabel.Text = Utils.ModuleCredits().GetCurrencyRateByDate(DateTime.Now.Date, (int)Constants.Constants.CurrencyList.USD).ToString();
                    break;

                case "addEditCreditPanel":
                    addEditCreditPanel.Visible = true;
                    creditAllDetailsPanel.Visible = true;
                    ClearAddEditLoanForm();
                    FillValidatorsOnNewCreditForm();
                    SetInitialRowForNewClientsTable();
                    UpdateManualEditCreditGridView();
                    //usdChangeRatelabel.Text = Utils.ModuleCredits().GetCurrencyRateByDate(DateTime.Now.Date, (int)Constants.Constants.CurrencyList.USD).ToString();
                    break;             

                case "emptyPanel":
                    emptyPanel.Visible = true;
                    break;

                default:
                    emptyPanel.Visible = true;
                    break;
            }

            #endregion Get Panel Name
        }
        catch (Exception ex)
        {
            Utils.InfoText(this, "Atentie! Eroare in sistem!", ex.Message);
        }
    }
      
    protected void addNewloanButton_Click(object sender, EventArgs e)
    {
        ClearAddEditLoanForm();
        ShowPanel(addEditCreditPanel.ID);
    }     

    protected void loanSelectionDialog_Selected(object sender, LoanSelectionDialog.FilterWindowEventsArg e)
    {
        Credits.DataObjects.LoanObject loanObject = Utils.ModuleCredits().GetLoanObjectByID(e.SelectedItem);
        this.CurrentCredit = loanObject;
        this.ClientObject = Utils.ModuleCredits().GetCleintObjectByID(loanObject.ClientID);
        FillAddEditForm();
        FillManualEditCreditGridView();
        ShowPanel(EditCreditPanel);
        CalculateTotalsLabelOnManualEditGridView();
        this.NewContract = false;
    }
    
    #region Add New/Edit Loan

    protected void FillDLLOnAddEditForm()
    {
        DataTable programList = Utils.ModuleMain().GetClassifierByTypeID((int)Constants.Constants.ClassifierTypes.Programs);
        Utils.FillSelector(loanProgramDDL, programList, "Name", "Code");

        DataTable productList = Utils.ModuleCredits().GetLoanProductsDisplayList();
        Utils.FillSelector(loanProdusDDL, productList, "productName", "productID");
        
        DataTable payperiodList = Utils.ModuleMain().GetClassifierByTypeID((int)Constants.Constants.ClassifierTypes.PayPeriod);
        Utils.FillSelector(payPeriodDDL, payperiodList, "Name", "Code");

        DataTable creditLinesList = Utils.ModuleCredits().GetFundingLinesList();
        Utils.FillSelector(creditLineDDL, creditLinesList, "Name", "LinesID");

        DataTable contrCategList = Utils.ModuleMain().GetClassifierByTypeID((int)Constants.Constants.ClassifierTypes.contractCategory);
        Utils.FillSelector(loanCategoryDDL, contrCategList, "Name", "Code");

        DataTable contractStatesList = Utils.ModuleMain().GetClassifierByTypeID((int)Constants.Constants.ClassifierTypes.CreditState);
        Utils.FillSelector(creditStateDDL, contractStatesList, "Name", "Code");

        DataTable userList = Utils.ModuleSecurity().UsersList();
        Utils.FillSelector(loanCreatorDDL, userList, "UserFullName", "userid");

        DataTable currencyDT = new DataTable();
        currencyDT.Columns.Add("code", typeof(int));
        currencyDT.Columns.Add("name", typeof(string));
        currencyDT.Rows.Add((int)Constants.Constants.CurrencyList.USD,"USD");
        currencyDT.Rows.Add((int)Constants.Constants.CurrencyList.EURO,"EURO");
        Utils.FillSelector(referenceCurrencyDDL, currencyDT, "Name", "Code");   
    }

    protected void ClearAddEditLoanForm()
    {
        Credits.DataObjects.Client clientObject = this.ClientObject;
        loanClientSelectedIDHiddenField.Value = clientObject.ClientID.ToString();
        loanClientDescription.Text = clientObject.FirstName + " " + clientObject.LastName + " : " + clientObject.BirthDate.ToString(Constants.Constants.ISODateBackwardDotsFormat);

        this.NewContract = true;
        requestDateTextBox.Text = DateTime.Now.ToString(Constants.Constants.ISODateBackwardDotsFormat);

        contractAmountLabel.Text = string.Empty;
        contractAmountTextBox.Text = string.Empty;

        paymentsCountLabel.Text = string.Empty;
        loanNrOfMonthsTextBox.Text = string.Empty;
            
        contractPercetLabel.Text = string.Empty;
        contractPercentTextBox.Text = string.Empty;        
        
        penaltyGracePeriodTextBox.Text = "0";

        calculateDinSoldInitialRadioButton.Checked = true;
        calculateDinSoldRamasRadioButton.Checked = false;
        
        loanScopeTextBox.Text = string.Empty;

        contractCodeTextBox.Text = Utils.ModuleCredits().GetNextAviableContractCode().ToString(); 
        loanDataContractelorTextBox.Text = string.Empty;
        loandDataEliberariiTextBox.Text = DateTime.Now.ToString(Constants.Constants.ISODateBackwardDotsFormat);

        loanDataScadenteiTextBox.Text = string.Empty;
        loanDataScadenteiTextBox.Text = string.Empty;

        currencyChangeRateTextBox.Text = string.Empty;

        garantiiFidejusoriListBox.Items.Clear();
        garantiiGajIpotecaListBox.Items.Clear();
        
        try { loanProgramDDL.SelectedValue = ((int)Constants.Constants.Classifiers.ContractProgram_StartUp).ToString(); }
        catch { }
        
        loanProdusDDL.SelectedIndex = 0;
        penaltyValue_HiddenField.Value = string.Empty;
        calculatePenaltyFrom_HiddenField.Value = string.Empty;

        creditLineDDL.SelectedIndex = 0;

        try { payPeriodDDL.SelectedValue = ((int)Constants.Constants.Classifiers.MonthlyPayment).ToString(); }
        catch { }

        try { loanCreatorDDL.SelectedValue = Utils.UserObject().UserID.ToString(); }
        catch { }

        try { referenceCurrencyDDL.SelectedIndex = 0;}
        catch { }
 
        ViewState[manualEditCreditCurrentTable] = null;
        UpdateManualEditCreditGridView();

        CreateUpdateViewStateTables();
        messagesListBox.Items.Clear();
        comitetMemberFilter.SelectedValues = new List<string>();
        this.FidejusoriList = null;  
    }

    protected void loanProdusDDL_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillValidatorsOnNewCreditForm();
    }      
   
    protected void FillGarantiiFidejusoriListBox()
    {
        List<Credits.DataObjects.Fidejusor> futgi = this.FidejusoriList;
        garantiiFidejusoriListBox.DataSource = null;
        garantiiFidejusoriListBox.Items.Clear();
        garantiiFidejusoriListBox.DataBind();

        if (futgi != null && futgi.Count > 0)
        {
            garantiiFidejusoriListBox.DataSource = futgi;
            garantiiFidejusoriListBox.DataTextField = "FidejusorFullDescription";
            garantiiFidejusoriListBox.DataValueField = "OrderID";
            garantiiFidejusoriListBox.DataBind();
        }
    }

    protected void garantFudjiClient_ClientSelected(object sender, ClientSelectionControl.FilterWindowEventsArg e)
    {
        if (e.SelectedItem != 0)
        {
            List<Credits.DataObjects.Fidejusor> futjiList = this.FidejusoriList;
            Credits.DataObjects.Fidejusor newFidej = new Credits.DataObjects.Fidejusor();
            newFidej.OrderID = futjiList.Count + 1;
            newFidej.FidejusorID =  e.SelectedItem;
            newFidej.FidejusorFirstLastName = garantFudjiClient.ClientFirstLastName;
            newFidej.FidejusorBirthDate = garantFudjiClient.SelectedClientBirthDate;
            newFidej.FidejusorIDNO = garantFudjiClient.SelectedClientIDNO;
            newFidej.FidejusorFullDescription = newFidej.OrderID.ToString() + ". " + newFidej.FidejusorFirstLastName + " (" + newFidej.FidejusorBirthDate.ToString(Constants.Constants.ISODateBackwardDotsFormat) + ")";

            int contractCode = 0;
            int.TryParse(contractCodeTextBox.Text, out contractCode);
            newFidej.ContractCode = this.CurrentCredit.ContractCode != 0 ? this.CurrentCredit.ContractCode : contractCode;
            
            futjiList.Add(newFidej);
            this.FidejusoriList = futjiList;

            FillGarantiiFidejusoriListBox();
            FillContractImprumutPrintForm();
        }
    }
 
    protected void addGarantiiFidejusoriButton_Click(object sender, EventArgs e)
    {
        garantFudjiClient.BindDataSource();
        garantFudjiClient.Show();
        FillContractImprumutPrintForm();
    }

    protected void removeGarantiiFidejusoriButton_Click(object sender, EventArgs e)
    {
        if (garantiiFidejusoriListBox.SelectedValue != null && this.FidejusoriList != null && this.FidejusoriList.Count > 0)
        {
            List<Credits.DataObjects.Fidejusor> futjiList = this.FidejusoriList;

            int orderID = 0;
            int.TryParse(garantiiFidejusoriListBox.SelectedValue, out orderID);
           
            for (int i = 0; i < futjiList.Count; i++)
            {
                Credits.DataObjects.Fidejusor current = futjiList[i];

                if (current.OrderID == orderID)
                {
                    futjiList.Remove(current);
                    i = futjiList.Count + 2;
                }
            }            
        }

        FillGarantiiFidejusoriListBox();
        FillContractImprumutPrintForm();
    }

    protected void gajControl_OkClick(object sender, PledgeForm.FilterWindowEventsArg e)
    {
        if (e.SelectedItem != null && ViewState["ipotGaj"] != null)
        {
            Hashtable resultGaj = e.SelectedItem;
            DataTable ipotGaj = (DataTable)ViewState["ipotGaj"];

            if (gajControl.CurrentOperation.Equals(Constants.Constants.UserOperation.New))
            {
                ipotGaj.Rows.Add();

                int LoanID = this.CurrentCredit.LoanID;
                int pledgeID = ipotGaj.Rows.Count;

                ipotGaj.Rows[ipotGaj.Rows.Count - 1]["LoanID"] = LoanID;
                ipotGaj.Rows[ipotGaj.Rows.Count - 1]["pledgeID"] = pledgeID;
                ipotGaj.Rows[ipotGaj.Rows.Count - 1]["ShortDescription"] = (string)resultGaj["ShortDescription"];
                ipotGaj.Rows[ipotGaj.Rows.Count - 1]["denumirea"] = (string)resultGaj["denumirea"];
                ipotGaj.Rows[ipotGaj.Rows.Count - 1]["pledgeType"] = (int)resultGaj["pledgeType"];
                ipotGaj.Rows[ipotGaj.Rows.Count - 1]["proprietar"] = (int)resultGaj["proprietar"];
                ipotGaj.Rows[ipotGaj.Rows.Count - 1]["address"] = (string)resultGaj["address"];
                ipotGaj.Rows[ipotGaj.Rows.Count - 1]["description"] = (string)resultGaj["description"];
                ipotGaj.Rows[ipotGaj.Rows.Count - 1]["pretpiata"] = (int)resultGaj["pretpiata"];
                ipotGaj.Rows[ipotGaj.Rows.Count - 1]["sumagajata"] = (int)resultGaj["sumagajata"];
            }
            else
            {              
                //for (int i = 0; i < ipotGaj.Rows.Count; i++)
                //{
                //    int registeredLoanID = (int)ipotGaj.Rows[i]["LoanID"];
                //    int registeredPledgeID = (int)ipotGaj.Rows[i]["pledgeID"];
                //    if (LoanID == registeredLoanID && registeredPledgeID == pledgeID)
                //    {
                //        ipotGaj.Rows[i]["ShortDescription"] = (string)resultGaj["ShortDescription"];
                //        ipotGaj.Rows[i]["denumirea"] = (string)resultGaj["denumirea"];
                //        ipotGaj.Rows[i]["pledgeType"] = (int)resultGaj["pledgeType"];
                //        ipotGaj.Rows[i]["proprietar"] = (int)resultGaj["proprietar"];
                //        ipotGaj.Rows[i]["address"] = (string)resultGaj["address"];
                //        ipotGaj.Rows[i]["description"] = (string)resultGaj["description"];
                //        ipotGaj.Rows[i]["pretpiata"] = (int)resultGaj["pretpiata"];
                //        ipotGaj.Rows[i]["sumagajata"] = (int)resultGaj["sumagajata"];

                //        i = ipotGaj.Rows.Count + 1;
                //    }
                //}
            }        

            FillGajIpotecaListBox();
        }
    }

    protected void FillGajIpotecaListBox()
    {
        if (ViewState["ipotGaj"] != null)
        {
            DataTable ipotGaj = (DataTable)ViewState["ipotGaj"];

            garantiiGajIpotecaListBox.DataSource = ipotGaj;
            garantiiGajIpotecaListBox.DataTextField = "ShortDescription";
            garantiiGajIpotecaListBox.DataValueField = "pledgeID";
            garantiiGajIpotecaListBox.DataBind();
        }
    }

    protected void addGajIpotecaButton_Click(object sender, EventArgs e)
    {       
        gajControl.CurrentOperation = Constants.Constants.UserOperation.New;
        gajControl.Show();
        FillContractImprumutPrintForm();
    }

    protected void removeGajIpotecaButtonButton_Click(object sender, EventArgs e)
    {
        if (garantiiGajIpotecaListBox.SelectedValue != null && ViewState["ipotGaj"] != null)
        {
            DataTable ipotGaj = (DataTable)ViewState["ipotGaj"];

            int selectedPledgeID = 0;
            int.TryParse(garantiiGajIpotecaListBox.SelectedValue, out selectedPledgeID);

            if (ipotGaj.Rows.Count > 0 && selectedPledgeID != 0)
            {
                for (int i = 0; i < ipotGaj.Rows.Count; i++)
                {
                    int ipod = (int)ipotGaj.Rows[i]["pledgeID"];

                    if (ipod == selectedPledgeID)
                    {
                        ipotGaj.Rows[i].Delete();
                        ipotGaj.AcceptChanges();
                        i = ipotGaj.Rows.Count + 2;
                    }
                }
            }
        }

        FillGajIpotecaListBox();
        FillContractImprumutPrintForm();
    }
    
    protected void FillMessagesListBox()
    {
        messagesListBox.Items.Clear();

        if (this.CurrentCredit != null)
        {
            int loanID = this.CurrentCredit.LoanID;

            DataTable dt = Utils.ModuleCredits().GetAprovesListStatusByLoanIDForShortDisplay(loanID);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                messagesListBox.Items.Add(dt.Rows[i]["UserApruveStatus"].ToString());
            }

            messagesListBox.Attributes["Onclick"] = "doPost('ShowMessages', '" + loanID + "');";
        }
    }
    
    protected void loanComitetCommentControl_MessagesUpdated(object sender, LoanComment.LoanCommentEventsArg e)
    {
        if (e.MesageStatusUpdated)
        {
            FillMessagesListBox();
        }
    }
    
    protected void FillAddEditForm()
    {
        try 
        {
            ClearAddEditLoanForm(); 

            Credits.DataObjects.LoanObject loanInfo = this.CurrentCredit;

            if (loanInfo != null)
            {
                try
                {
                    loanProdusDDL.SelectedValue = loanInfo.ProductID.ToString();
                    FillValidatorsOnNewCreditForm();
                }
                catch { }

                requestDateTextBox.Text = loanInfo.RequestDate != DateTime.MinValue ? loanInfo.RequestDate.ToString(Constants.Constants.ISODateBackwardDotsFormat) : string.Empty;
                loanClientSelectedIDHiddenField.Value = loanInfo.ClientID.ToString();

                Credits.DataObjects.Client clientObject = this.ClientObject;
                loanClientDescription.Text = clientObject.FirstName + " " + clientObject.LastName + " : " + clientObject.BirthDate.ToString(Constants.Constants.ISODateBackwardDotsFormat);

                contractAmountTextBox.Text = loanInfo.ContractAmount.ToString();
                loanNrOfMonthsTextBox.Text = loanInfo.NrOfCreditMonth.ToString();
                contractPercentTextBox.Text = loanInfo.ContrcatPercent.ToString();
                penaltyGracePeriodTextBox.Text = loanInfo.PenaltyGracePeriod.ToString();

                int calculatePercentFrom = loanInfo.CalculatePenaltyFrom;
                switch (calculatePercentFrom)
                {
                    case (int)Constants.Constants.Classifiers.Percent_DinSumaInitiala:
                        calculateDinSoldInitialRadioButton.Checked = true;
                        calculateDinSoldRamasRadioButton.Checked = false;
                        break;

                    case (int)Constants.Constants.Classifiers.Percent_DinSumaRamasa:
                        calculateDinSoldInitialRadioButton.Checked = false;
                        calculateDinSoldRamasRadioButton.Checked = true;
                        break;
                }

                loanScopeTextBox.Text = loanInfo.LoanScope;

                contractCodeTextBox.Text = loanInfo.ContractCode.ToString();
                loanDataContractelorTextBox.Text = loanInfo.ContractDate != DateTime.MinValue ? loanInfo.ContractDate.ToString(Constants.Constants.ISODateBackwardDotsFormat) : string.Empty;
                loandDataEliberariiTextBox.Text = loanInfo.LoanStartDate.ToString(Constants.Constants.ISODateBackwardDotsFormat);
                loanDataScadenteiTextBox.Text = loanInfo.LoanEndDate.ToString(Constants.Constants.ISODateBackwardDotsFormat);
                currencyChangeRateTextBox.Text = loanInfo.CurrencyChangeRate.ToString();

                try { loanProgramDDL.SelectedValue = loanInfo.LoanProgramID.ToString(); }
                catch { }

                penaltyValue_HiddenField.Value = loanInfo.ContractPenalty.ToString();
                calculatePenaltyFrom_HiddenField.Value = loanInfo.CalculatePenaltyFrom.ToString();

                try { creditLineDDL.SelectedValue = loanInfo.FundingLineID.ToString(); }
                catch { }

                try { payPeriodDDL.SelectedValue = loanInfo.PayPeriodID.ToString(); }
                catch { }

                try { loanCategoryDDL.SelectedValue = loanInfo.LoanCategoryID.ToString(); }
                catch { }

                try { referenceCurrencyDDL.SelectedValue = loanInfo.CurrencyID.ToString(); }
                catch { }

                try { loanCreatorDDL.SelectedValue = loanInfo.LoanManagerID.ToString(); }
                catch { }

                try { creditStateDDL.SelectedValue = loanInfo.LoanState != 0 ? loanInfo.LoanState.ToString() : ((int)Constants.Constants.Classifiers.CreditState_InAsteptareAprobare).ToString(); }
                catch { }

                CreateUpdateViewStateTables();

                DataTable ipotGajDT = Utils.ModuleCredits().GetPledgeListByLoanID(loanInfo.LoanID);
                ViewState["ipotGaj"] = ipotGajDT;
                FillGajIpotecaListBox();

                this.FidejusoriList = Utils.ModuleCredits().GetLoanFidejusoriObjectListByLoanID(loanInfo.LoanID);
                FillGarantiiFidejusoriListBox();
                
                FillMessagesListBox();
                analizComentControl.LoanID = loanInfo.LoanID;
                LoanDelaysCommentsControl.LoanID = loanInfo.LoanID;

                comitetMemberFilter.SelectedValues = Utils.ModuleCredits().GetRegisteredComitetMemberList(loanInfo.LoanID);

                ViewState[manualEditCreditCurrentTable] = Utils.ModuleCredits().GetLoanOrderList(loanInfo.LoanID);    

                FillContractImprumutPrintForm();

                SetLoanEditAviability();
            }
        }
        catch (Exception ex)
        { Utils.InfoText(this, "Eroare in System!", ex.Message.ToString()); } 
    }

    protected void SetLoanEditAviability()
    {
        bool AllowEdit = true;

        Credits.DataObjects.LoanObject loanInfo = this.CurrentCredit;

        if (loanInfo != null)
        {
            AllowEdit = loanInfo.LoanState != (int)Constants.Constants.Classifiers.CreditState_Activ || loanInfo.LoanManagerID == Utils.UserObject().UserID;
        }

        requestDateTextBox.ReadOnly = !AllowEdit;
        requestDateTextBox.Enabled = AllowEdit;

        //loanClientDescription.ReadOnly = !AllowEdit;
        //loanClientDescription.Enabled = AllowEdit;

        contractAmountTextBox.ReadOnly = !AllowEdit;
        contractAmountTextBox.Enabled = AllowEdit;

        loanNrOfMonthsTextBox.ReadOnly = !AllowEdit;
        loanNrOfMonthsTextBox.Enabled = AllowEdit;

        contractPercentTextBox.ReadOnly = !AllowEdit;
        contractPercentTextBox.Enabled = AllowEdit;

        alternativePercentTextBox.ReadOnly = !AllowEdit;
        alternativePercentTextBox.Enabled = AllowEdit;

        penaltyGracePeriodTextBox.ReadOnly = !AllowEdit;
        penaltyGracePeriodTextBox.Enabled = AllowEdit;

        loanScopeTextBox.ReadOnly = !AllowEdit;
        loanScopeTextBox.Enabled = AllowEdit;

        contractCodeTextBox.ReadOnly = !AllowEdit;
        contractCodeTextBox.Enabled = AllowEdit;

        loanDataContractelorTextBox.ReadOnly = !AllowEdit;
        loanDataContractelorTextBox.Enabled = AllowEdit;

        loandDataEliberariiTextBox.ReadOnly = !AllowEdit;
        loandDataEliberariiTextBox.Enabled = AllowEdit;

        loanDataScadenteiTextBox.ReadOnly = !AllowEdit;
        loanDataScadenteiTextBox.Enabled = AllowEdit;

        currencyChangeRateTextBox.ReadOnly = !AllowEdit;
        currencyChangeRateTextBox.Enabled = AllowEdit;

        messagesListBox.Enabled = AllowEdit;
        garantiiGajIpotecaListBox.Enabled = AllowEdit;
        garantiiFidejusoriListBox.Enabled = AllowEdit;
        calculateDinSoldRamasRadioButton.Enabled = AllowEdit;
        calculateDinSoldInitialRadioButton.Enabled = AllowEdit;
        payPeriodDDL.Enabled = AllowEdit;
        loanProgramDDL.Enabled = AllowEdit;
        loanProdusDDL.Enabled = AllowEdit;
        creditLineDDL.Enabled = AllowEdit;
        creditStateDDL.Enabled = AllowEdit;
        referenceCurrencyDDL.Enabled = AllowEdit;
        getCurrencyButton.Enabled = AllowEdit;
        loanCreatorDDL.Enabled = AllowEdit;
        loanCategoryDDL.Enabled = AllowEdit;


        saveLoanButton.Visible = AllowEdit;
        saveLoanButton.Enabled = AllowEdit;

        addGarantiiFidejusoriButton.Visible = AllowEdit;
        addGarantiiFidejusoriButton.Enabled = AllowEdit;

        removeGarantiiFidejusoriButton.Visible = AllowEdit;
        removeGarantiiFidejusoriButton.Enabled = AllowEdit;

        addGajIpotecaButton.Visible = AllowEdit;
        addGajIpotecaButton.Enabled = AllowEdit;

        removeGajIpotecaButtonButton.Visible = AllowEdit;
        removeGajIpotecaButtonButton.Enabled = AllowEdit;

        saveloanOrdersButton.Visible = AllowEdit;
        saveloanOrdersButton.Enabled = AllowEdit;

        initialLoanOrdersButton.Visible = AllowEdit;
        initialLoanOrdersButton.Enabled = AllowEdit;

        manualEditCreditGridView.Enabled = AllowEdit;

        comitetMemberFilter.Visible = AllowEdit;
    }

    protected void saveLoanButton_Click(object sender, EventArgs e)
    {
        if (allowLoanEdit)
        {
            int clientID = 0;
            int.TryParse(loanClientSelectedIDHiddenField.Value, out clientID);

            if (clientID != 0)
            {
                Credits.DataObjects.LoanObject loanObject = this.CurrentCredit;

                #region Prepare Input Dates
                loanObject.ClientID = clientID;

                int programID = 0;
                int.TryParse(loanProgramDDL.SelectedValue, out programID);
                loanObject.ProgramID = programID;

                int productId = 0;
                int.TryParse(loanProdusDDL.SelectedValue, out productId);
                loanObject.ProductID = productId;

                int contractCode = 0;
                int.TryParse(contractCodeTextBox.Text, out contractCode);
                loanObject.ContractCode = contractCode;

                int perioadaImprumutului = 0;
                int.TryParse(loanNrOfMonthsTextBox.Text, out perioadaImprumutului);
                loanObject.NrOfCreditMonth = perioadaImprumutului;

                int loanCreator = 0;
                int.TryParse(loanCreatorDDL.SelectedValue, out loanCreator);
                loanObject.LoanManagerID = loanCreator;

                DateTime loanStartDate = Crypt.Utils.ToDateTime(loandDataEliberariiTextBox.Text, Constants.Constants.ISODateBackwardDotsFormat);
                loanObject.LoanStartDate = loanStartDate;
                DateTime loanEndDate = loanStartDate;
                if (!loanDataScadenteiTextBox.Text.Equals(string.Empty))
                {
                    loanEndDate = Crypt.Utils.ToDateTime(loanDataScadenteiTextBox.Text, Constants.Constants.ISODateBackwardDotsFormat);
                }
                else
                {                    
                    loanEndDate = loanStartDate.AddMonths(perioadaImprumutului);
                    loanDataScadenteiTextBox.Text = loanEndDate.ToString(Constants.Constants.ISODateBackwardDotsFormat);
                }
                loanObject.LoanEndDate = loanEndDate;

                int payPariod = 0;
                int.TryParse(payPeriodDDL.SelectedValue, out payPariod);
                loanObject.PayPeriodID = payPariod;

                int foundingLineID = 0;
                int.TryParse(creditLineDDL.SelectedValue, out foundingLineID);
                loanObject.FundingLineID = foundingLineID;

                loanObject.ContractAmount = Crypt.Utils.MyDecimalParce(contractAmountTextBox.Text); 
                loanObject.ContrcatPercent = Crypt.Utils.MyDecimalParce(contractPercentTextBox.Text); 

                int calculatePercentFrom = 0;
                if (calculateDinSoldInitialRadioButton.Checked) calculatePercentFrom = (int)Constants.Constants.Classifiers.Percent_DinSumaInitiala;
                if (calculateDinSoldRamasRadioButton.Checked) calculatePercentFrom = (int)Constants.Constants.Classifiers.Percent_DinSumaRamasa;
                loanObject.CalculatePercentFrom = calculatePercentFrom;

                int calculatePenaltyFrom = 0;
                int.TryParse(calculatePenaltyFrom_HiddenField.Value, out calculatePenaltyFrom);
                loanObject.CalculatePenaltyFrom = calculatePenaltyFrom;

                loanObject.ContractPenalty = Crypt.Utils.MyDecimalParce(penaltyValue_HiddenField.Value); 

                int penaltyGracePeriod = 0;
                int.TryParse(penaltyGracePeriodTextBox.Text, out penaltyGracePeriod);
                loanObject.PenaltyGracePeriod = penaltyGracePeriod;

                loanObject.LoanScope = loanScopeTextBox.Text;
                loanObject.ModifiedBy = Utils.UserObject().UserID;                

                int loanCategory = 0;
                int.TryParse(loanCategoryDDL.SelectedValue, out loanCategory);
                loanObject.LoanCategoryID = loanCategory;

                int currencyID = 0;
                int.TryParse(referenceCurrencyDDL.SelectedValue, out currencyID);
                loanObject.CurrencyID = currencyID;

                loanObject.CurrencyChangeRate = Crypt.Utils.MyDecimalParce(currencyChangeRateTextBox.Text);

                int contractState = 0;
                int.TryParse(creditStateDDL.SelectedValue, out contractState);
                loanObject.LoanState = contractState != 0 ? contractState : (int)Constants.Constants.Classifiers.CreditState_InAsteptareAprobare;

                loanObject.RequestDate = Crypt.Utils.ToDateTime(requestDateTextBox.Text, Constants.Constants.ISODateBackwardDotsFormat);
                loanObject.ContractDate = Crypt.Utils.ToDateTime(loanDataContractelorTextBox.Text, Constants.Constants.ISODateBackwardDotsFormat);

                #endregion Prepare Input Dates

                bool updateLoanReult = false;                
                bool isCurretOperationNew = this.NewContract;

                if (isCurretOperationNew)
                {
                    updateLoanReult = Utils.ModuleCredits().AddNewLoan(loanObject);
                    this.NewContract = false;
                }
                else
                {
                    if (loanObject.LoanID != 0)
                    {
                        updateLoanReult = Utils.ModuleCredits().UpdateLoan(loanObject);
                        this.NewContract = false;
                    }
                }

                if (updateLoanReult && loanObject.LoanID != 0)
                {
                    this.CurrentCredit = loanObject;

                    if (ViewState["ipotGaj"] != null)
                    {
                        DataTable ipoGaj = (DataTable)ViewState["ipotGaj"];
                        if (ipoGaj != null && ipoGaj.Rows.Count > 0)
                        {
                            int succesifulyInsertedIpotGaj = 0;

                            for (int i = 0; i < ipoGaj.Rows.Count; i++)
                            {
                                int pledgeID = isCurretOperationNew ? i : (int)ipoGaj.Rows[i]["pledgeID"];
                                string denumirea = (string)ipoGaj.Rows[i]["denumirea"];
                                int pledgeType = (int)ipoGaj.Rows[i]["pledgeType"];
                                int proprietar = (int)ipoGaj.Rows[i]["proprietar"];
                                string address = (string)ipoGaj.Rows[i]["address"];
                                string description = (string)ipoGaj.Rows[i]["description"];
                                int pretpiata = (int)ipoGaj.Rows[i]["pretpiata"];
                                int sumagajata = (int)ipoGaj.Rows[i]["sumagajata"];

                                if (Utils.ModuleCredits().AddLoanPledgesDetails(loanObject.LoanID, pledgeID, loanObject.LoanVersion, denumirea, pledgeType, proprietar, address, description, pretpiata, sumagajata))
                                { succesifulyInsertedIpotGaj++; }
                            }
                        }
                    }

                    if (this.FidejusoriList != null)
                    {
                        List<Credits.DataObjects.Fidejusor> futjiList = this.FidejusoriList;
                        if (futjiList != null && futjiList.Count > 0)
                        {
                            int succesifulyInsertedFutji = 0;

                            for (int i = 0; i < futjiList.Count; i++)
                            {
                                if (futjiList[i].FidejusorID != 0)
                                {
                                    futjiList[i].OrderID = i + 1;
                                    if (Utils.ModuleCredits().AddLoanFidejusori(loanObject.LoanID, futjiList[i].FidejusorID, futjiList[i].OrderID))
                                    { succesifulyInsertedFutji++; }
                                }
                            }

                            this.FidejusoriList = Utils.ModuleCredits().GetLoanFidejusoriObjectListByLoanID(loanObject.LoanID);
                            FillGarantiiFidejusoriListBox();
                        }
                    }


                    if (comitetMemberFilter.SelectedValues.Count > 0)
                    {
                        Utils.ModuleCredits().UpdateComitetMembers(loanObject.LoanID, comitetMemberFilter.SelectedValuesAsInt);
                        FillMessagesListBox();
                    }

                    FillContractImprumutPrintForm();
                    ShowPanel(EditCreditPanel);

                    Utils.InfoText(this, "Success!", "Creditul a fost salvat cu success!");
                    SetLoanEditAviability();
                    loanSelectionDialog.BindDataSource();
                }
                else
                {
                    Utils.InfoText(this, "Erorare!", "Creditul nu a fost salvat! Verificati va rog datele.");
                }
            }
            else
            {
                Utils.InfoText(this, "Atentie!", "Alegeti va rog un client!");
            }
        }
        else
        {
            Response.Redirect(Utils.GetApplicationPath(Request) + "/AccessDenied.aspx");
        }
    }

    protected void previewLoanButton_Click(object sender, EventArgs e)
    {
        int loanID = this.CurrentCredit.LoanID;

        if (loanID != 0)
        {
            DataTable orderList = Utils.ModuleCredits().GetLoanOrderList(loanID);
            if (orderList != null && orderList.Rows.Count > 0)
            {
                ViewState[manualEditCreditCurrentTable] = orderList;
            }
            else
            {
                SetInitialRowForNewClientsTable();
            }

            UpdateManualEditCreditGridView();
            creditAllDetailsContainer.ActiveTabIndex = 5;
        }

        SetLoanEditAviability();
        FillContractImprumutPrintForm();
    }

    protected void initialLoanOrdersButton_Click(object sender, EventArgs e)
    {
        decimal currencyChangeRate = Crypt.Utils.MyDecimalParce(currencyChangeRateTextBox.Text);

        ViewState[manualEditCreditCurrentTable] = PrepareLoanOrders(currencyChangeRate);
        UpdateManualEditCreditGridView();
        CalculateTotalsLabelOnManualEditGridView();    
        creditAllDetailsContainer.ActiveTabIndex = 5;

        SetLoanEditAviability();
        FillContractImprumutPrintForm();
    }

    protected void FillValidatorsOnNewCreditForm()
    {
        int productID = 0;
        int.TryParse(loanProdusDDL.SelectedValue, out productID);

        if (Utils.ModuleCredits() != null && productID != 0)
        {
            DataTable productInfo = Utils.ModuleCredits().GetLoanProductByID(productID);
            if (productInfo != null && productInfo.Rows.Count == 1)
            {
                #region set CreditAmountRangeValidator
                string contractAmountMaxVal = "1000000000";
                string contractAmountMinVal = "0";
                int creditAmountValue = 0;
                int.TryParse(productInfo.Rows[0]["creditAmountValue"].ToString(), out creditAmountValue);

                if (creditAmountValue == 0)
                {
                    contractAmountTextBox.ReadOnly = false;

                    if (!productInfo.Rows[0]["creditAmountMax"].ToString().Equals(string.Empty))
                        contractAmountMaxVal = productInfo.Rows[0]["creditAmountMax"].ToString();

                    if (!productInfo.Rows[0]["creditAmountMin"].ToString().Equals(string.Empty))
                        contractAmountMinVal = productInfo.Rows[0]["creditAmountMin"].ToString();

                    //contractAmount_RangeValidator.MaximumValue = contractAmountMaxVal;
                    //contractAmount_RangeValidator.MinimumValue = contractAmountMinVal;

                    contractAmountLabel.Text = "(Min:" + contractAmountMinVal + " Max:" + contractAmountMaxVal + ") ";
                }
                else
                {
                    contractAmountTextBox.ReadOnly = true;
                    contractAmountLabel.Text = "(" + creditAmountValue + ")";
                    contractAmountTextBox.Text = creditAmountValue.ToString();
                    //contractAmount_RangeValidator.MaximumValue = creditAmountValue.ToString();
                    //contractAmount_RangeValidator.MinimumValue = creditAmountValue.ToString();
                }
                #endregion set CreditAmountRangeValidator

                #region set contractPercent_RangeValidator
                string percentMax = "100";
                string percentMin = "0";
                decimal percentValue = 0;
                decimal.TryParse(productInfo.Rows[0]["percentValue"].ToString(), out percentValue);


                if ((int)productInfo.Rows[0]["calculatePercentFrom"] == (int)Constants.Constants.Classifiers.SumaFixa)
                {
                    calculateDinSoldInitialRadioButton.Checked = false;
                    calculateDinSoldRamasRadioButton.Checked = false;
                    //calculateSumaFixaRadioButton.Checked = true;
                    contractPercetLabel.Text = "Suma fixa";
                    //contractPercent_RangeValidator.Enabled = false;
                    contractPercentTextBox.Text = percentValue.ToString();
                }
                else
                {
                    if ((int)productInfo.Rows[0]["calculatePercentFrom"] == (int)Constants.Constants.Classifiers.Percent_DinSumaRamasa)
                    {
                        calculateDinSoldInitialRadioButton.Checked = false;
                        calculateDinSoldRamasRadioButton.Checked = true;
                        //calculateSumaFixaRadioButton.Checked = false;                        
                    }
                    if ((int)productInfo.Rows[0]["calculatePercentFrom"] == (int)Constants.Constants.Classifiers.Percent_DinSumaInitiala)
                    {
                        calculateDinSoldInitialRadioButton.Checked = true;
                        calculateDinSoldRamasRadioButton.Checked = false;
                        //calculateSumaFixaRadioButton.Checked = false;
                    }

                    //contractPercent_RangeValidator.Enabled = true;

                    if (percentValue == 0)
                    {
                        contractPercentTextBox.ReadOnly = false;

                        if (!productInfo.Rows[0]["percentMax"].ToString().Equals(string.Empty))
                            percentMax = productInfo.Rows[0]["percentMax"].ToString();

                        if (!productInfo.Rows[0]["percentMin"].ToString().Equals(string.Empty))
                            percentMin = productInfo.Rows[0]["percentMin"].ToString();

                        //contractPercent_RangeValidator.MaximumValue = percentMax;
                        //contractPercent_RangeValidator.MinimumValue = percentMin;

                        contractPercetLabel.Text = "(Min:" + percentMin + " Max:" + percentMax + ")";
                    }
                    else
                    {
                        contractPercentTextBox.ReadOnly = true;
                        contractPercetLabel.Text = "(" + percentValue + ")";
                        contractPercentTextBox.Text = percentValue.ToString();
                        //contractPercent_RangeValidator.MaximumValue = percentValue.ToString();
                        //contractPercent_RangeValidator.MinimumValue = percentValue.ToString();
                    }
                }
                #endregion set contractPercent_RangeValidator
                              
                #region set paymnetsCount_RangeValidator
                string paymnetsCountMax = "1000";
                string paymnetsCountMin = "0";
                int paymnetsCountValue = 0;
                int.TryParse(productInfo.Rows[0]["paymnetsCountValue"].ToString(), out paymnetsCountValue);

                if (paymnetsCountValue == 0)
                {
                    loanNrOfMonthsTextBox.ReadOnly = false;

                    if (!productInfo.Rows[0]["paymnetsCountMax"].ToString().Equals(string.Empty))
                        paymnetsCountMax = productInfo.Rows[0]["paymnetsCountMax"].ToString();

                    if (!productInfo.Rows[0]["paymentsCountMin"].ToString().Equals(string.Empty))
                        paymnetsCountMin = productInfo.Rows[0]["paymentsCountMin"].ToString();

                    creditPeriodCount_RangeValidator.MaximumValue = paymnetsCountMax;
                    creditPeriodCount_RangeValidator.MinimumValue = paymnetsCountMin;

                    paymentsCountLabel.Text = "(Min:" + paymnetsCountMin + " Max:" + paymnetsCountMax + ") ";
                }
                else
                {
                    loanNrOfMonthsTextBox.ReadOnly = true;
                    paymentsCountLabel.Text = "(" + paymnetsCountValue + ")";
                    loanNrOfMonthsTextBox.Text = paymnetsCountValue.ToString();
                    creditPeriodCount_RangeValidator.MaximumValue = paymnetsCountValue.ToString();
                    creditPeriodCount_RangeValidator.MinimumValue = paymnetsCountValue.ToString();
                }
                #endregion set paymnetsCount_RangeValidator

                calculatePenaltyFrom_HiddenField.Value = productInfo.Rows[0]["calculatePenaltyFrom"].ToString();
                penaltyValue_HiddenField.Value = productInfo.Rows[0]["penaltyPercentValue"].ToString();
            }
        }
    }

    #endregion Add New/Edit Loan    
     
    protected DataTable PrepareLoanOrders(decimal currencyChangeRate)
    {
        DateTime loanStartDate = Crypt.Utils.ToDateTime(loandDataEliberariiTextBox.Text, Constants.Constants.ISODateBackwardDotsFormat);

        decimal creditAmount = Crypt.Utils.MyDecimalParce(contractAmountTextBox.Text);
        decimal creditPercent = Crypt.Utils.MyDecimalParce(contractPercentTextBox.Text);

        int nrTotalLuniACreditului = 0;
        int.TryParse(loanNrOfMonthsTextBox.Text, out nrTotalLuniACreditului);

        int payPeriodCode = 0;
        int.TryParse(payPeriodDDL.SelectedValue, out payPeriodCode);

        int calculatePernectFromCode = 0;
        if (calculateDinSoldInitialRadioButton.Checked) calculatePernectFromCode = (int)Constants.Constants.Classifiers.Percent_DinSumaInitiala;
        if (calculateDinSoldRamasRadioButton.Checked) calculatePernectFromCode = (int)Constants.Constants.Classifiers.Percent_DinSumaRamasa;

        DateTime loanEdnDate = DateTime.MinValue;
        DataTable grafic = Credits.Module.PrepareOrdersTable(loanStartDate, creditAmount, creditPercent, nrTotalLuniACreditului, payPeriodCode, calculatePernectFromCode, currencyChangeRate, out loanEdnDate);
        grafic.Columns.Add("manualmodifed", typeof(bool));

        if (loanDataScadenteiTextBox.Text.Equals(string.Empty))
        loanDataScadenteiTextBox.Text = loanEdnDate.ToString(Constants.Constants.ISODateBackwardDotsFormat);

        return grafic;
    }

    #region Manual Edit Credit

    protected void FillManualEditCreditGridView()
    {
        UpdateManualEditCreditGridView();
    }

    private void SetInitialRowForNewClientsTable()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("iterationID", typeof(string)));
        dt.Columns.Add(new DataColumn("calculatedData", typeof(DateTime)));
        dt.Columns.Add(new DataColumn("days", typeof(int)));
        dt.Columns.Add(new DataColumn("percentValue", typeof(decimal)));
        dt.Columns.Add(new DataColumn("mainRate", typeof(decimal)));
        dt.Columns.Add(new DataColumn("manualmodifed", typeof(bool)));
        dt.Columns.Add(new DataColumn("TotalAmount", typeof(decimal)));
        dt.Columns.Add(new DataColumn("remainingAmount", typeof(decimal)));
        dt.Columns.Add(new DataColumn("currencyChangeRate", typeof(decimal)));
        dt.Columns.Add(new DataColumn("totalAmount_Rated", typeof(decimal)));

        dr = dt.NewRow();
        dr["iterationID"] = 1;

        dt.Rows.Add(dr);

        ViewState[manualEditCreditCurrentTable] = dt;
        manualEditCreditGridView.DataSource = dt;
        manualEditCreditGridView.DataBind();
    }

    private void UpdateManualEditCreditGridView()
    {
        if (ViewState[manualEditCreditCurrentTable] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState[manualEditCreditCurrentTable];

            if (dtCurrentTable != null)
            {
                manualEditCreditGridView.DataSource = dtCurrentTable;
                manualEditCreditGridView.DataBind();

                DateTime maxModifiedDate = DateTime.MinValue;

                for (int i = 0; i < dtCurrentTable.Rows.Count; i++)
                {
                    Label nrLabel = (Label)manualEditCreditGridView.Rows[i].Cells[0].FindControl("nrLabel");
                    TextBox manualEditCreditDataTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[1].FindControl("manualEditCreditDataTextBox");
                    TextBox daysLabel = (TextBox)manualEditCreditGridView.Rows[i].Cells[2].FindControl("daysLabel");
                    TextBox manualEditCreditRemainingAmountTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[3].FindControl("manualEditCreditRemainingAmountTextBox");
                    TextBox manualEditMainRateTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[4].FindControl("manualEditMainRateTextBox");
                    HiddenField manualEditMainRateModifiedHiddenField = (HiddenField)manualEditCreditGridView.Rows[i].Cells[4].FindControl("manualEditMainRateModifiedHiddenField");
                    TextBox percentTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[5].FindControl("percentTextBox");
                    TextBox manualEditCreditTotalAmountTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[6].FindControl("manualEditCreditTotalAmountTextBox");
                    TextBox manualEditCreditTotalAmount_RatedTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[7].FindControl("manualEditCreditTotalAmount_RatedTextBox");
                    
                    nrLabel.Text = (i + 1).ToString();

                    DateTime calculatedDate = dtCurrentTable.Rows[i]["calculatedData"] != System.DBNull.Value ? ((DateTime)dtCurrentTable.Rows[i]["calculatedData"]) : DateTime.MinValue;
                    manualEditCreditDataTextBox.Text = calculatedDate != DateTime.MinValue ? calculatedDate.ToString(Constants.Constants.ISODateBackwardDotsFormat) : string.Empty;
                    if (calculatedDate > maxModifiedDate)
                    {
                        maxModifiedDate = calculatedDate;
                    }

                    if (dtCurrentTable.Rows[i]["days"] != System.DBNull.Value)
                    {
                        daysLabel.Text = dtCurrentTable.Rows[i]["days"].ToString();// ? ().ToString() : string.Empty;
                    }
                    else
                    {
                        if (dtCurrentTable.Rows[i]["calculatedData"] != System.DBNull.Value)
                        {
                            DateTime currentDate = (DateTime)dtCurrentTable.Rows[i]["calculatedData"];
                            DateTime previousDate = DateTime.MinValue;
                            if (i == 0)
                            { previousDate = Crypt.Utils.ToDateTime(loandDataEliberariiTextBox.Text, Constants.Constants.ISODateBackwardDotsFormat); }
                            else
                            {
                                if (dtCurrentTable.Rows[i - 1]["calculatedData"] != System.DBNull.Value)
                                previousDate = (DateTime)dtCurrentTable.Rows[i - 1]["calculatedData"]; 
                            }
                            daysLabel.Text = (currentDate - previousDate).Days.ToString();
                        }
                    }

                    manualEditCreditRemainingAmountTextBox.Text = dtCurrentTable.Rows[i]["remainingAmount"] != System.DBNull.Value ? dtCurrentTable.Rows[i]["remainingAmount"].ToString() : string.Empty;
                    manualEditMainRateTextBox.Text = dtCurrentTable.Rows[i]["mainRate"] != System.DBNull.Value ? dtCurrentTable.Rows[i]["mainRate"].ToString() : string.Empty;
                    percentTextBox.Text = dtCurrentTable.Rows[i]["percentValue"] != System.DBNull.Value ? dtCurrentTable.Rows[i]["percentValue"].ToString() : string.Empty;
                    manualEditCreditTotalAmountTextBox.Text = dtCurrentTable.Rows[i]["TotalAmount"] != System.DBNull.Value ? dtCurrentTable.Rows[i]["TotalAmount"].ToString() : string.Empty;
                    manualEditCreditTotalAmount_RatedTextBox.Text = dtCurrentTable.Rows[i]["TotalAmount_Rated"] != System.DBNull.Value ? dtCurrentTable.Rows[i]["TotalAmount_Rated"].ToString() : string.Empty;

                    manualEditMainRateModifiedHiddenField.Value = dtCurrentTable.Rows[i]["manualmodifed"] != System.DBNull.Value && (bool)dtCurrentTable.Rows[i]["manualmodifed"] == true ? "true" : "false";

                    /// manual  add  events

                    //manualEditCreditDataTextBox.Attributes.Add("onchange", "CalculateData(this, " + (i + 1).ToString() + ");");
                    //manualEditCreditDataTextBox.Attributes.Add("onKeyUp", "CalculateData(this, " + (i + 1).ToString() + ");");

                    manualEditMainRateTextBox.Attributes.Add("onKeyUp", "ModifiedRate(" + (i + 1).ToString() + ", '" + manualEditCreditGridView.ClientID + "', '" + contractAmountTextBox.ClientID + "', '" + loandDataEliberariiTextBox.ClientID + "', '" + loanDataScadenteiTextBox.ClientID + "', '" + contractPercentTextBox.ClientID + "', '" + calculateDinSoldInitialRadioButton.ClientID + "', '" + currencyChangeRateTextBox.ClientID + "', '" + loanNrOfMonthsTextBox.ClientID + "', '" + payPeriodDDL.ClientID + "');");
                    manualEditCreditTotalAmountTextBox.Attributes.Add("onKeyUp", "ModifiedTotalAmount(" + (i + 1).ToString() + ", '" + manualEditCreditGridView.ClientID + "', '" + contractAmountTextBox.ClientID + "', '" + loandDataEliberariiTextBox.ClientID + "', '" + loanDataScadenteiTextBox.ClientID + "', '" + contractPercentTextBox.ClientID + "', '" + calculateDinSoldInitialRadioButton.ClientID + "', '" + currencyChangeRateTextBox.ClientID + "','" + loanNrOfMonthsTextBox.ClientID + "', '" + payPeriodDDL.ClientID + "');");

                    percentTextBox.Attributes.Add("readonly", "readonly");
                    daysLabel.Attributes.Add("readonly", "readonly");
                    manualEditCreditRemainingAmountTextBox.Attributes.Add("readonly", "readonly");
                }

                if (maxModifiedDate != DateTime.MinValue)
                    loanDataScadenteiTextBox.Text = maxModifiedDate.ToString(Constants.Constants.ISODateBackwardDotsFormat);
            }
        }
    }

    private DataTable SaveLastChangesInManualEditCreditGridView()
    {
        DataTable dtCurrentTable = null;

        if (ViewState[manualEditCreditCurrentTable] != null)
        {
            dtCurrentTable = (DataTable)ViewState[manualEditCreditCurrentTable];
            decimal currencyChangeRate = Crypt.Utils.MyDecimalParce(currencyChangeRateTextBox.Text);

            if (dtCurrentTable != null)
            {
                for (int i = 0; i < dtCurrentTable.Rows.Count; i++)
                {
                    Label nrLabel = (Label)manualEditCreditGridView.Rows[i].Cells[0].FindControl("nrLabel");
                    TextBox manualEditCreditDataTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[1].FindControl("manualEditCreditDataTextBox");
                    TextBox daysLabel = (TextBox)manualEditCreditGridView.Rows[i].Cells[2].FindControl("daysLabel");
                    TextBox manualEditCreditRemainingAmountTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[3].FindControl("manualEditCreditRemainingAmountTextBox");
                    TextBox manualEditMainRateTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[4].FindControl("manualEditMainRateTextBox");
                    TextBox percentTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[5].FindControl("percentTextBox");
                    TextBox manualEditCreditTotalAmountTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[6].FindControl("manualEditCreditTotalAmountTextBox");
                    TextBox manualEditCreditTotalAmount_RatedTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[7].FindControl("manualEditCreditTotalAmount_RatedTextBox");

                    HiddenField manualEditMainRateModifiedHiddenField = (HiddenField)manualEditCreditGridView.Rows[i].Cells[4].FindControl("manualEditMainRateModifiedHiddenField");

                    dtCurrentTable.Rows[i]["iterationID"] = (i + 1).ToString();

                    if (!manualEditCreditDataTextBox.Text.Equals(string.Empty))
                    {
                        DateTime tempDate = Crypt.Utils.ToDateTime(manualEditCreditDataTextBox.Text, Constants.Constants.ISODateBackwardDotsFormat);
                        if (!tempDate.Equals(DateTime.MinValue))
                        {
                            dtCurrentTable.Rows[i]["calculatedData"] = tempDate;
                            if (DateTime.Now.Date > tempDate)
                            {
                                dtCurrentTable.Rows[i]["currencyChangeRate"] = currencyChangeRate;
                            }
                        }                       
                    }

                    if (!percentTextBox.Text.Equals(string.Empty))
                    {
                        decimal tempVal = Crypt.Utils.MyDecimalParce(percentTextBox.Text);
                        dtCurrentTable.Rows[i]["percentValue"] = tempVal;
                    }

                    if (!daysLabel.Text.Equals(string.Empty))
                    {
                        int tempVal = 0;
                        int.TryParse(daysLabel.Text, out tempVal);
                        dtCurrentTable.Rows[i]["days"] = tempVal;
                    }

                    if (!manualEditMainRateTextBox.Text.Equals(string.Empty))
                    {
                        decimal tempVal = Crypt.Utils.MyDecimalParce(manualEditMainRateTextBox.Text);
                        dtCurrentTable.Rows[i]["mainRate"] = tempVal;
                    }

                    if (!manualEditCreditTotalAmountTextBox.Text.Equals(string.Empty))
                    {
                        decimal tempVal = Crypt.Utils.MyDecimalParce(manualEditCreditTotalAmountTextBox.Text);
                        dtCurrentTable.Rows[i]["TotalAmount"] = tempVal;
                    }

                    if (!manualEditCreditRemainingAmountTextBox.Text.Equals(string.Empty))
                    {
                        decimal tempVal = Crypt.Utils.MyDecimalParce(manualEditCreditRemainingAmountTextBox.Text);
                        dtCurrentTable.Rows[i]["remainingAmount"] = tempVal;
                    }

                    if (!manualEditCreditTotalAmount_RatedTextBox.Text.Equals(string.Empty))
                    {
                        decimal tempVal = Crypt.Utils.MyDecimalParce(manualEditCreditTotalAmount_RatedTextBox.Text);
                        dtCurrentTable.Rows[i]["TotalAmount_Rated"] = tempVal;
                    }

                    dtCurrentTable.Rows[i]["manualmodifed"] = manualEditMainRateModifiedHiddenField.Value.Equals("true");
                }
            }
        }
        else
        {
            Utils.InfoText(this, "Error on page!", "ViewState is null");
        }

        ViewState[manualEditCreditCurrentTable] = dtCurrentTable;
        return dtCurrentTable;
    }

    protected void manualEditCreditButtonAdd_Click(object sender, EventArgs e)
    {
        DataTable dtCurrentTable = SaveLastChangesInManualEditCreditGridView();

        if (dtCurrentTable != null && dtCurrentTable.Columns.Count > 0)
        {
            dtCurrentTable.Rows.Add();
            dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["iterationID"] = dtCurrentTable.Rows.Count;

            if (dtCurrentTable.Rows.Count > 2 && dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 2]["calculatedData"] != System.DBNull.Value)
            {
                DateTime previousDate = (DateTime)dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 2]["calculatedData"];
                DateTime newEnteredDate = previousDate.AddMonths(1);
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["calculatedData"] = newEnteredDate;
                int days = (newEnteredDate - previousDate).Days;
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["days"] = days;
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["percentValue"] = 0;
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["mainRate"] = 0;
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["TotalAmount"] = 0;
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["remainingAmount"] = 0;
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["currencyChangeRate"] = 0;
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["totalAmount_Rated"] = 0;
            }

            loanNrOfMonthsTextBox.Text = dtCurrentTable.Rows.Count.ToString();
            ViewState[manualEditCreditCurrentTable] = dtCurrentTable;
        }

        UpdateManualEditCreditGridView();
        CalculateTotalsLabelOnManualEditGridView();
        FillContractImprumutPrintForm();
    }

    protected void manualEditCreditGridView_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
    {
        int index = e.RowIndex;

        DataTable dtCurrentTable = SaveLastChangesInManualEditCreditGridView();

        if (dtCurrentTable != null && dtCurrentTable.Columns.Count > 0)
        {
            dtCurrentTable.Rows[index].Delete();
            dtCurrentTable.AcceptChanges();

            loanNrOfMonthsTextBox.Text = dtCurrentTable.Rows.Count.ToString();
            ViewState[manualEditCreditCurrentTable] = dtCurrentTable;
        }

        UpdateManualEditCreditGridView();
        CalculateTotalsLabelOnManualEditGridView();
        FillContractImprumutPrintForm();
    }

    private const string manualEditCreditCurrentTable = "manualEditCreditCurrentTable";

    private void CalculateTotalsLabelOnManualEditGridView()
    {
        decimal totalPercent = 0;
        decimal totalMainRate = 0;
        decimal totalAmount = 0;
        decimal totalDays = 0;
        decimal totalAmountRated = 0;
        decimal initialAmount = Crypt.Utils.MyDecimalParce(contractAmountTextBox.Text);

        if (manualEditCreditGridView != null && manualEditCreditGridView.Rows != null)
        {
            for (int i = 0; i < manualEditCreditGridView.Rows.Count; i++)
            {
                TextBox daysLabel = (TextBox)manualEditCreditGridView.Rows[i].Cells[2].FindControl("daysLabel");
                TextBox manualEditMainRateTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[4].FindControl("manualEditMainRateTextBox");
                TextBox percentTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[5].FindControl("percentTextBox");
                TextBox manualEditCreditTotalAmountTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[6].FindControl("manualEditCreditTotalAmountTextBox");
                TextBox manualEditCreditTotalAmount_RatedTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[7].FindControl("manualEditCreditTotalAmount_RatedTextBox");

                int tempTotalDays = 0;
                int.TryParse(daysLabel.Text, out tempTotalDays);
                totalDays += tempTotalDays;

                decimal tempPercent = Crypt.Utils.MyDecimalParce(percentTextBox.Text);
                totalPercent += tempPercent;

                decimal tempMainrate = Crypt.Utils.MyDecimalParce(manualEditMainRateTextBox.Text);
                totalMainRate += tempMainrate;

                decimal temptotalAmount = Crypt.Utils.MyDecimalParce(manualEditCreditTotalAmountTextBox.Text);
                totalAmount += temptotalAmount;

                decimal temptotalAmountRated = Crypt.Utils.MyDecimalParce(manualEditCreditTotalAmount_RatedTextBox.Text);
                totalAmountRated += temptotalAmountRated;
            }

            if (manualEditCreditGridView.FooterRow != null)
            {
                Label totalDaysLabel = manualEditCreditGridView.FooterRow.FindControl("totalDaysLabel") as Label;
                if (totalDaysLabel != null)
                {
                    totalDaysLabel.Text = totalDays.ToString();
                }

                Label manualEditCreditTotalProcetLabel = manualEditCreditGridView.FooterRow.FindControl("manualEditCreditTotalProcetLabel") as Label;
                if (manualEditCreditTotalProcetLabel != null)
                {
                    manualEditCreditTotalProcetLabel.Text = totalPercent.ToString();
                }

                Label manualEditCreditTotalmainRateLabel = manualEditCreditGridView.FooterRow.FindControl("manualEditCreditTotalmainRateLabel") as Label;
                if (manualEditCreditTotalmainRateLabel != null)
                {
                    manualEditCreditTotalmainRateLabel.Text = totalMainRate.ToString();
                }

                Label manualEditCreditTotalAmountLabel = manualEditCreditGridView.FooterRow.FindControl("manualEditCreditTotalAmountLabel") as Label;
                if (manualEditCreditTotalAmountLabel != null)
                {
                    manualEditCreditTotalAmountLabel.Text = totalAmount.ToString();
                }

                Label manualEditCreditTotalTotalAmount_RatedLabel = manualEditCreditGridView.FooterRow.FindControl("manualEditCreditTotalTotalAmount_RatedLabel") as Label;
                if (manualEditCreditTotalTotalAmount_RatedLabel != null)
                {
                    manualEditCreditTotalTotalAmount_RatedLabel.Text = totalAmountRated.ToString();
                }
            }
        }
    }
    
    #endregion Manual Edit Credit

    protected void loanClientInfoButton_Click(object sender, EventArgs e)
    {
        int clientID = 0;
        int.TryParse(loanClientSelectedIDHiddenField.Value, out clientID);

        if (clientID != 0)
        {
            clientInfoControl.ClientID = clientID;
            clientInfoControl.Show();
            SetLoanEditAviability();
            FillContractImprumutPrintForm();
        }
    }    
    
    protected void PaymentListButton_Click(object sender, EventArgs e)
    {
        int loanID = this.CurrentCredit.LoanID;

        if (loanID != 0)
        {
            Response.Redirect("PaymentByList.aspx?loanID=" + loanID.ToString());
        }
    }

    protected void PersonalFolderButton_Click(object sender, EventArgs e)
    {
        try
        {
            int clientID = 0;
            int.TryParse(loanClientSelectedIDHiddenField.Value, out clientID);

            if (clientID != 0)
            {

                Credits.DataObjects.Client clientObject = Utils.ModuleCredits().GetCleintObjectByID(clientID);
                if (clientObject != null)
                {
                    clientObject = Utils.ModuleCredits().CheckClientPersonalFolders(clientObject, Server.MapPath(Utils.ModuleCredits().RootModuleFolder));
                    personalFileBrowser.TitleWindow = "Mapa Personala pentru: " + clientObject.FirstName + " " + clientObject.LastName;
                    personalFileBrowser.RootDirectory = Utils.ModuleCredits().RootModuleFolder + "/" + clientObject.ClientPersonalFolder + "/" + "PersonalDocuments";
                    personalFileBrowser.Show();

                    SetLoanEditAviability();
                    FillContractImprumutPrintForm();
                }
            }
        }
        catch
        { }
    }

    protected void comitetMemberFilter_EntrySelected(object sender, FilterWindow.FilterWindowEventsArg e)
    {
        Utils.ModuleCredits().UpdateComitetMembers(this.CurrentCredit.LoanID, comitetMemberFilter.SelectedValuesAsInt);
        FillMessagesListBox();
        FillContractImprumutPrintForm();
    }

    protected void saveloanOrdersButton_Click(object sender, EventArgs e)
    {
         DataTable loanOrdersTable = SaveLastChangesInManualEditCreditGridView();

         if (loanOrdersTable != null && loanOrdersTable.Rows.Count > 0)
         {
             int loanID = this.CurrentCredit.LoanID;

             if (loanID != 0)
             {
                 decimal currencyChangeRate = Crypt.Utils.MyDecimalParce(currencyChangeRateTextBox.Text);
                 Utils.ModuleCredits().ClearLoanOrderForLoanID(loanID);
                 int successInserted = 0;

                 /// adding LoanOrders
                 for (int i = 0; i < loanOrdersTable.Rows.Count; i++)
                 {
                     if (loanOrdersTable.Rows[i]["calculatedData"] != System.DBNull.Value)
                     {
                         DateTime calculatedDate = (DateTime)loanOrdersTable.Rows[i]["calculatedData"];
                         int days = (int)loanOrdersTable.Rows[i]["days"];
                         decimal percentAmount = Crypt.Utils.MyDecimalParce(loanOrdersTable.Rows[i]["percentValue"].ToString().Replace(",", ".")); 
                         decimal mainRate = Crypt.Utils.MyDecimalParce(loanOrdersTable.Rows[i]["mainRate"].ToString().Replace(",", "."));
                         decimal remainingAmount = Crypt.Utils.MyDecimalParce(loanOrdersTable.Rows[i]["remainingAmount"].ToString().Replace(",", ".")); 
                         bool manualmodifed = loanOrdersTable.Rows[i]["manualmodifed"] != null ? (bool)loanOrdersTable.Rows[i]["manualmodifed"] : false;

                         if (Utils.ModuleCredits().AddNewLoanOrder(loanID, i, calculatedDate, days, percentAmount, mainRate, remainingAmount, currencyChangeRate, manualmodifed))
                         {
                             successInserted++;
                         }
                     }
                 }

                 if (successInserted == loanOrdersTable.Rows.Count)
                 {
                     Utils.InfoText(this, "Success!", "Graficul a fost salvat cu success!");
                 }
                 else
                 {
                     Utils.InfoText(this, "ATENTIE!", "GRAFICUL NU A FOST SALVAT IN INTREGIME - VERIFICATI DATELE !");
                 }
             }
             else
             {
                 Utils.InfoText(this, "Atentie!", "Mai intii trebuie sa salvati un credit si dupa aceea sa creati un grafic de achitari pentru el!");
             }
         }

         SetLoanEditAviability();
         FillContractImprumutPrintForm();
    }

    protected void FillCurrencyRatetextBox()
    {
        DateTime dataContract = Crypt.Utils.ToDateTime(loanDataContractelorTextBox.Text, Constants.Constants.ISODateBackwardDotsFormat);
        int currencyID = 0;
        int.TryParse(referenceCurrencyDDL.SelectedValue, out currencyID);

        decimal currencyChangeRate = Utils.ModuleCredits().GetCurrencyRateByDate(dataContract, currencyID);
        currencyChangeRateTextBox.Text = currencyChangeRate.ToString();
    }

    protected void referenceCurrencyDDL_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillCurrencyRatetextBox();
    }

    protected void getCurrencyButton_Click(object sender, EventArgs e)
    {
        FillCurrencyRatetextBox();
        FillContractImprumutPrintForm();
    }

    #region PrintForm Region       

    protected void FillContractImprumutPrintForm()
    {
        AccordionPane AccordionPane = new AccordionPane();
        AccordionPane.ID = "AccordionPane_Contract";

        ////////////////////////////  CONTRACT
        LiteralControl contrLiteral = new LiteralControl();
        contrLiteral.Text = "CONTRACT DE IMPRUMUT ";
        contrLiteral.ID = "contrLiteral";
        AccordionPane.HeaderContainer.Controls.Add(contrLiteral);

        ContractsPrintForm_Control contractPrintForm = (ContractsPrintForm_Control)LoadControl("~/Controls/ContractsPrintForm_Control.ascx");
        contractPrintForm.PrepareViewContract(this.CurrentCredit, this.FidejusoriList);

        Button printContractFormButton = new Button();
        printContractFormButton.ID = "printContractFormButton";
        printContractFormButton.Text = "Print";
        printContractFormButton.Height = 19;
        AccordionPane.HeaderContainer.Controls.Add(printContractFormButton);

        AccordionPane.ContentContainer.Controls.Add(contractPrintForm);
        printFormAccordion.Panes.Add(AccordionPane);
        printContractFormButton.Attributes["onclick"] = "showPrintWindow('" + contractPrintForm.PrintAreaID + "', '" + printFontSizeSelector.SelectedValue + "'); return false;";
        ////////////////////////////////////////////////////

        DataTable dtCurrentTable = (DataTable)ViewState[manualEditCreditCurrentTable];
        DataTable newSourceTable = dtCurrentTable != null ? Crypt.Utils.AddTotalsToTable(dtCurrentTable.Copy(), "calculatedData", "Total:", new List<string>(new string[] { "mainRate", "percentValue", "totalAmount", "totalAmount_Rated", "mainRate_Rated" })) : null;

        if (newSourceTable != null && newSourceTable.Rows.Count > 0)
        {
            bool displayMainRateRated = addAmountratedToPrintFormCheckBox.Checked;

            /////////////////// GRAFIC
            AccordionPane AccordionPaneG = new AccordionPane();
            AccordionPaneG.ID = "AccordionPane_ContractG";

            LiteralControl contrLiteralG = new LiteralControl();
            contrLiteralG.Text = "ANEXA 1 - GRAFICUL DE IMPRUMUT ";
            contrLiteralG.ID = "contrLiteral";
            AccordionPaneG.HeaderContainer.Controls.Add(contrLiteralG);

            Button printContractFormButtonG = new Button();
            printContractFormButtonG.ID = "printContractFormButton";
            printContractFormButtonG.Text = "Print";
            printContractFormButtonG.Height = 19;
            AccordionPaneG.HeaderContainer.Controls.Add(printContractFormButtonG);

            GridView grafic = new GridView();
            grafic.ID = "GraficGridView";

            int selectedSize = 0;
            int.TryParse(printFontSizeSelector.SelectedValue, out selectedSize);

            grafic.Style.Add("font-size", (9 + selectedSize).ToString());
            grafic.Style.Add("margin", "0px auto");
            grafic.Style.Add("width", "80%");
            grafic.AutoGenerateColumns = false;

            BoundField nrColumn = new BoundField();
            nrColumn.DataField = "iterationID";
            nrColumn.HeaderText = "Nr.";

            BoundField dataColumn = new BoundField();
            dataColumn.DataFormatString = "{0:dd.MM.yyyy}";
            dataColumn.DataField = "calculatedData";
            dataColumn.HeaderText = "Data";
            dataColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Center;

            BoundField daysColumn = new BoundField();
            daysColumn.DataField = "days";
            daysColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            daysColumn.HeaderText = "Zile";

            BoundField remainingAmColumn = new BoundField();
            remainingAmColumn.DataField = "remainingAmount";
            remainingAmColumn.HeaderText = "Suma ramasa";
            remainingAmColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Right;

            BoundField mainRateColumn = new BoundField();
            mainRateColumn.DataField = "mainRate";
            mainRateColumn.HeaderText = "Rata imprumutului";
            mainRateColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Right;

            BoundField percentColumn = new BoundField();
            percentColumn.DataField = "percentValue"; 
            percentColumn.HeaderText = "Dobinda";
            percentColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Right;

            BoundField totalAmountColumn = new BoundField();
            totalAmountColumn.DataField = "totalAmount"; 
            totalAmountColumn.HeaderText = "Suma Totala";
            totalAmountColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Right;

            BoundField totalAmountRatedColumn = new BoundField();
            totalAmountRatedColumn.DataField = "totalAmount_Rated"; 
            totalAmountRatedColumn.HeaderText = "Suma Totala in " + referenceCurrencyDDL.SelectedItem.Text;
            totalAmountRatedColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Right;

            BoundField mainRateRatedColumn = new BoundField();
            mainRateRatedColumn.DataField = "mainRate_Rated";
            mainRateRatedColumn.HeaderText = "Rata imprumutului in " + referenceCurrencyDDL.SelectedItem.Text;
            mainRateRatedColumn.ItemStyle.HorizontalAlign = HorizontalAlign.Right;

            grafic.Columns.Add(nrColumn);
            grafic.Columns.Add(dataColumn);
            grafic.Columns.Add(daysColumn);
            grafic.Columns.Add(remainingAmColumn);
            grafic.Columns.Add(mainRateColumn);

            if(displayMainRateRated)
                grafic.Columns.Add(mainRateRatedColumn);

            grafic.Columns.Add(percentColumn);
            grafic.Columns.Add(totalAmountColumn);

            if(displayMainRateRated)
            grafic.Columns.Add(totalAmountRatedColumn);

            grafic.DataSource = newSourceTable;
            grafic.DataBind();

            grafic.Rows[grafic.Rows.Count - 1].Cells[3].Text = "0";
            grafic.Rows[grafic.Rows.Count - 1].Cells[1].Text = "Total:";

            Panel divPanel = new Panel();
            divPanel.ID = "anexaGraficDiv";


            #region header of Anexe

            string literalcontrolString = string.Empty;

            literalcontrolString += "ANEXA nr. 1. la Contractul de împrumut nr. " + this.CurrentCredit.ContractCode + " din " + this.CurrentCredit.ContractSpecificStartDate + " <br> <br>";
            literalcontrolString += " <div style=\"text-align:center; text-transform:uppercase; margin-bottom:10px; \"> \r\n ";
            literalcontrolString += " Graficul de rambursare a ratelor împrumutului şi dobînzilor \r\n ";
            literalcontrolString += " </div> \r\n ";

            literalcontrolString += " <div style=\"width:48%; float:left; \"> \r\n ";
            literalcontrolString += " 	<span id=\"MainContent_label1\" style=\"display:inline-block;width:59%;text-align:right; \">Suma imprumutului, lei:</span> \r\n ";
            literalcontrolString += " 	<span id=\"MainContent_loanAmountLabel\" style=\"display:inline-block;width:39%;text-align:left;\">" + this.CurrentCredit.ContractAmount + "</span> \r\n ";
            literalcontrolString += " 	<br> \r\n ";
            literalcontrolString += " 	<span id=\"MainContent_label2\" style=\"display:inline-block;width:59%;text-align:right;\">Rata anuala a dobinzii, %:</span> \r\n ";
            literalcontrolString += " 	<span id=\"MainContent_loanPercetLabel\" style=\"display:inline-block;width:39%;text-align:left;\">" + this.CurrentCredit.ContrcatPercent + "</span> \r\n ";
            literalcontrolString += " 	<br> \r\n ";
            literalcontrolString += " 	<span id=\"MainContent_label3\" style=\"display:inline-block;width:59%;text-align:right;\">Perioada rambursare rate:</span> \r\n ";
            literalcontrolString += " 	<span id=\"MainContent_loanCalculationMetodLabel\" style=\"display:inline-block;width:39%;text-align:left;\">" + this.CurrentCredit.PayPeriodIDString + "</span> \r\n ";
            literalcontrolString += " 	<br> \r\n ";
            literalcontrolString += " 	<span id=\"MainContent_label4\" style=\"display:inline-block;width:59%;text-align:right;\"></span> \r\n ";
            literalcontrolString += " 	<span id=\"MainContent_loanAmountInUSDLabel\" style=\"display:inline-block;width:39%;text-align:left;\"></span> \r\n ";
            literalcontrolString += " </div> \r\n ";

            literalcontrolString += " <div style=\"width:48%; float:left; \"> \r\n ";
            literalcontrolString += " 	<span id=\"MainContent_label5\" style=\"display:inline-block;width:49%;text-align:right;\">Termen, luni:</span> \r\n ";
            literalcontrolString += " 	<span id=\"MainContent_loanStartDateLabel\" style=\"display:inline-block;width:49%;text-align:left;\">" + this.CurrentCredit.NrOfCreditMonth + "</span> \r\n ";
            literalcontrolString += " 	<br> \r\n ";
            literalcontrolString += " 	<span id=\"MainContent_label7\" style=\"display:inline-block;width:49%;text-align:right;\">Nr. de transe:</span> \r\n ";
            literalcontrolString += " 	<span id=\"MainContent_loanNrOfPaymnetsLabel\" style=\"display:inline-block;width:49%;text-align:left;\">" + this.CurrentCredit.NrOfCreditMonth + "</span> \r\n ";
            literalcontrolString += " 	<br>            \r\n ";
            literalcontrolString += " 	<br> \r\n ";
            literalcontrolString += " 	<span id=\"MainContent_currencyLabel\" style=\"display:inline-block;width:49%;text-align:right;\"></span> \r\n ";
            literalcontrolString += " 	<span id=\"MainContent_currencyChangeRatelabel\" style=\"display:inline-block;width:49%;text-align:left;\"></span> \r\n ";
            literalcontrolString += " </div> <div style=\"clear:both;\"></div> <br> \r\n ";
            literalcontrolString += " <b>Numele clientului:  " + this.CurrentCredit.ClientFirstLastName + " </b>  \r\n  <br><br>";

            divPanel.Controls.Add(new LiteralControl(literalcontrolString));
            #endregion header of Anexe

            divPanel.Controls.Add(grafic);

            string literalRechiziteString = string.Empty;

            literalRechiziteString += "<br>Declar că înţeleg şi sînt de acord cu modul prezentat de achitare a ratelor ";
            literalRechiziteString += "<br> împrumutului şi dobînzii şi că voi respecta acest mod de achitare.     <br> <br>    ";

            literalRechiziteString += "<div style=\"width:48%; float:left; text-align:center;\"> ";
            literalRechiziteString += "<b>CREDITOR</b> ";
            literalRechiziteString += "<br><br>";
            literalRechiziteString += "<br> _________________________";
            literalRechiziteString += "</div>";

            literalRechiziteString += "<div style=\"width:48%; float:left; text-align:center;\"> ";
            literalRechiziteString += "<b>DEBITOR</b> ";
            literalRechiziteString += "<br><br>";
            literalRechiziteString += "<br> _________________________";
            literalRechiziteString += "</div>";

            divPanel.Controls.Add(new LiteralControl(literalRechiziteString));

            AccordionPaneG.ContentContainer.Controls.Add(divPanel);
            printFormAccordion.Panes.Add(AccordionPaneG);
            printContractFormButtonG.Attributes["onclick"] = "showPrintWindow('" + divPanel.ClientID + "', '" + printFontSizeSelector.SelectedValue + "'); return false;";
        }
        //////////////////////////////////////

        for (int i = 0; i < this.FidejusoriList.Count; i++)
        {
            AccordionPane AccordionPaneF = new AccordionPane();
            AccordionPaneF.ID = "AccordionPaneF" + i;

            LiteralControl contrLiteralF = new LiteralControl();
            contrLiteralF.Text = "CONTRACT DE FIDEJUSIUNE " + FidejusoriList[i].ContractCode + " - " + FidejusoriList[i].OrderID + "  &nbsp;&nbsp;";
            contrLiteralF.ID = "contrLiteral" + i;
            AccordionPaneF.HeaderContainer.Controls.Add(contrLiteralF);

            ContractsFidejusiunePrintForm_Control contractPrintFormF = (ContractsFidejusiunePrintForm_Control)LoadControl("~/Controls/ContractsFidejusiunePrintForm_Control.ascx");
            contractPrintFormF.ID = "contractPrintFormF" + i;
            contractPrintFormF.PrepareViewContract(this.FidejusoriList[i]);

            Button printContractFFormButton = new Button();
            printContractFFormButton.ID = "printContractFormButtonF" + i;
            printContractFFormButton.Text = "Print";
            printContractFFormButton.Height = 19;
            AccordionPaneF.HeaderContainer.Controls.Add(printContractFFormButton);

            AccordionPaneF.ContentContainer.Controls.Add(contractPrintFormF);
            printFormAccordion.Panes.Add(AccordionPaneF);
            printContractFFormButton.Attributes["onclick"] = "showPrintWindow('" + contractPrintFormF.PrintAreaID + "', '" + printFontSizeSelector.SelectedValue + "'); return false;";
        }
    }

    protected void printFontSizeSelector_SelectedIndexChanged(object sender, EventArgs e)
    {
        SetLoanEditAviability();
        FillContractImprumutPrintForm();
    }

    #endregion PrintForm Region


    protected void addAmountratedToPrintFormCheckBox_CheckedChanged(object sender, EventArgs e)
    {
        FillContractImprumutPrintForm();
    }
}



    


